package com.imedway.ihe.dtz.xds.util;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.EnumMap;
import java.util.Map;

import org.openehealth.ipf.commons.ihe.xds.core.metadata.Timestamp.Precision;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DateUtils {

    private static final Map<Precision, SimpleDateFormat> FORMATTERS = new EnumMap<>(Precision.class);
    
    static {
        FORMATTERS.put(Precision.YEAR,   new SimpleDateFormat("yyyy"));
        FORMATTERS.put(Precision.MONTH,  new SimpleDateFormat("yyyyMM"));
        FORMATTERS.put(Precision.DAY,    new SimpleDateFormat("yyyyMMdd"));
        FORMATTERS.put(Precision.HOUR,   new SimpleDateFormat("yyyyMMddHH"));
        FORMATTERS.put(Precision.MINUTE, new SimpleDateFormat("yyyyMMddHHmm"));
        FORMATTERS.put(Precision.SECOND, new SimpleDateFormat("yyyyMMddHHmmss"));
    }
	 public static Timestamp changeTime(org.openehealth.ipf.commons.ihe.xds.core.metadata.Timestamp timestamp){
		 if(timestamp!=null) {
				org.openehealth.ipf.commons.ihe.xds.core.metadata.Timestamp  dTimestamp = timestamp;			
				
				SimpleDateFormat formatter=FORMATTERS.get(dTimestamp.getPrecision());	
			    Date date = null;
				try {
					date = formatter.parse(timestamp.toHL7());
				} catch (ParseException e) {
					e.printStackTrace();
				}    
	            return new Timestamp(date.getTime()); 
		 }else {
			 return null;
		 }	      
	 }
	 

	public static org.openehealth.ipf.commons.ihe.xds.core.metadata.Timestamp changeTime2(Timestamp timestamp){
		 if(timestamp!=null) {
				log.info(timestamp.toString());						
	         return org.openehealth.ipf.commons.ihe.xds.core.metadata.Timestamp.fromHL7(timestamp.toString().replace("-", "").replace(" ", "").replace(":", ""));
		 }else {
			 return null;
		 }	      
	 }
	
}
